import {designComponent, iHTMLDivElement, onMounted, PropType, reactive, useRefs} from "@peryl/react-compose";
import {loadFile} from '@peryl/utils/loadFile';
import {PlainObject} from "@peryl/utils/event";
import {LoadingMask} from "plain-design";

const getEcharts = (() => {
  let ret: any = undefined;
  return async () => {
    if (!ret) {
      ret = await loadFile('https://cdn.bootcdn.net/ajax/libs/echarts/5.6.0/echarts.min.js', 'echarts');
      console.log({ Echarts: ret });
    }
    return ret;
  };
})();

export const EchartsViewer = designComponent({
  props: {
    option: { type: Object as PropType<PlainObject>, required: true },
    height: { type: String, default: '300px' }
  },
  setup({ props }) {

    const { refs, onRef } = useRefs({ container: iHTMLDivElement });

    const state = reactive({
      getEcharts: null as null | (() => any),
      getInstance: () => null as null | PlainObject,
      loading: false,
    });

    onMounted(async () => {
      state.loading = true;
      const Echarts = await getEcharts();
      state.loading = false;

      state.getEcharts = () => Echarts;

      const instance = Echarts.init(refs.container!);
      state.getInstance = () => instance;

      instance.setOption(props.option);
    });

    return () => (
      <div style={{ height: props.height }}>
        <div ref={onRef.container} style={{ height: '100%' }}></div>
        <LoadingMask modelValue={state.loading}/>
      </div>
    );
  },
});
